package com.gengzp.gateway.utils;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;

/**
 * @ClassName HttpRequestUtils
 * @Description http请求工具类, 用于发送http请求
 * @Author gengzp
 * @Date 2025/9/24 10:26
 */
public class HttpRequestUtils {

    private static final HttpClient HTTP_CLIENT = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_2)
            .connectTimeout(Duration.ofSeconds(60))
            .build();

    private HttpRequestUtils() {
    }

    /**
     * 发送POST请求（同步）
     *
     * @param url     请求URL
     * @param body    请求体内容
     * @param headers 请求头信息
     * @return 响应字符串
     * @throws Exception 可能抛出的异常
     */
    public static String post(String url, String body, Map<String, String> headers) throws Exception {
        // 构建请求
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(Duration.ofSeconds(15))
                .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8));

        // 添加请求头
        if (headers != null && !headers.isEmpty()) {
            headers.forEach((k, v) -> {
                Optional.ofNullable(v).ifPresent(value -> requestBuilder.header(k, v));
            });
        } else {
            // 默认添加Content-Type
            requestBuilder.header("Content-Type", "application/json");
        }

        return HTTP_CLIENT.send(
                requestBuilder.build(),
                HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)).body();
    }

}
